package com.atguigu.tingshu.common.aspect;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.AuthLogin;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.lettuce.core.RedisException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect
@Component
public class AuthLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @execution: * com.atguigu.tingshu.*.api.*.*(..) 连接点: 所有表现层方法
     * @annotation: 执行注解
     * @pjp: 具体切入点对象
     * @authLogin: 执行具体注解
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(authLogin) ")
    public Object around(ProceedingJoinPoint pjp, AuthLogin authLogin) throws Throwable {
        //获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //查询Redis用户信息
        String token = request.getHeader("token");
        String tokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(tokenKey);
        //查询结果1: 无->用户未登录,跳转登录页面
        if (userInfoVo == null && authLogin.required()) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //查询结果2: 有->保存用户登录信息至本地线程
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
        }
        //执行目标方法
        Object result = pjp.proceed();
        //删除线程信息
        AuthContextHolder.removeUserId();
        return result;
    }
}
